﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.Security;

namespace Devmil.MVVM
{
    public class WeakReference<T> : WeakReference
    {
        [SecuritySafeCritical]
        public WeakReference() : base(default(T))
        { }

        public WeakReference(T target)
            : base(target)
        {
        }

        [SecuritySafeCritical]
        public WeakReference(T target, bool trackResurrection)
            : base(target, trackResurrection)
        {
        }

        new public T Target
        {
            get
            {
                return (T)base.Target;
            }
            set
            {
                base.Target = value;
            }
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
            if (obj is T)
            {
                if (!IsAlive)
                    return false;
                T castedObj = (T)obj;
                return Target.Equals(castedObj);
            }
            else if (obj is WeakReference<T>)
            {
                WeakReference<T> castedObj = (WeakReference<T>)obj;
                if (castedObj.IsAlive != IsAlive)
                    return false;
                if (!IsAlive)
                    return true;
                return Target.Equals(castedObj.Target);
            }
            return false;
        }

        public override int GetHashCode()
        {
            int result = 0;
            if (IsAlive)
                result = Target.GetHashCode();
            return result;
        }
    }
}
